import { CallLimitDetailInfo } from 'admin/schema/CorporateSet';
import {
  queryCallLimitDetail,
  queryCallLimitSwitch,
  updateCallLimitSwitch,
} from 'admin/servers/servers';
import { Button, message, Switch } from 'antd';
import { debounce } from 'lodash';
import React, { Component } from 'react';
import { DetailModal } from './component/DetailModal';
import './../style.scss';

interface Props {}
interface State {
  /**呼叫频次限制开关 */
  callLimitSwitch?: 'on' | 'off';
  callLimitDetail: CallLimitDetailInfo;
  visibleDetail: boolean;
  // 设置弹窗打开方式：0-开启，1-修改
  mode?: 0 | 1;
}

/**企业设置-呼叫频次限制 */
export default class CallLimit extends Component<Props, State> {
  state = {
    callLimitSwitch: undefined,
    callLimitDetail: {} as CallLimitDetailInfo,
    visibleDetail: false,
    mode: undefined,
  };
  componentDidMount() {
    this.fetchData();
  }
  /**查询数据 */
  fetchData = async () => {
    try {
      const { data } = await queryCallLimitSwitch();
      const { switchFlag } = data;
      this.setState({
        callLimitSwitch: switchFlag,
      });
      // 查询数据展示
      const res = await queryCallLimitDetail();
      if (res.data) {
        this.setState({
          callLimitDetail: { ...res.data },
        });
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };
  /**接口请求-启用停用 */
  updateSwitch = async (value: boolean) => {
    const newVal: 'on' | 'off' = value ? 'on' : 'off';
    const msg = value ? '启用' : '停用';
    const data = {
      switchFlag: newVal,
    };
    await updateCallLimitSwitch(data);
    message.success(msg + '成功');
    this.setState({
      callLimitSwitch: newVal,
      visibleDetail: value,
    });
  };

  /**操作-呼叫频次限制开关 */
  onSetChange = debounce((value: boolean) => {
    try {
      if (value) {
        // 1-启用步骤：需要先在设置弹窗操作【确定】按钮
        // 第一步：调设置修改接口
        // 第二步：调【启用】接口
        this.setState({
          mode: 0,
          visibleDetail: true,
        });
      } else {
        // 2-停用
        this.updateSwitch(false);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }, 500);

  /**编辑详情 */
  openDetail = debounce(() => {
    this.setState({ visibleDetail: true, mode: 1 });
  }, 500);

  /**关闭弹窗 */
  closeDetail = () => {
    this.setState({ visibleDetail: false, mode: undefined });
  };

  render() {
    const { callLimitSwitch, callLimitDetail, visibleDetail, mode } = this.state;
    const { dayAllowableTimes, weekAllowableTimes, monthAllowableTimes, halfYearAllowableTimes } =
      callLimitDetail;
    return (
      <div>
        <div className="box-header">呼叫频次限制</div>
        <div className="box">
          <div className="box-in">
            <p>限制号码在规定时间内的被呼叫次数，通话成功算作1次呼叫</p>
            {callLimitSwitch === 'on' && callLimitDetail && (
              <p className="grey list-span">
                {dayAllowableTimes && <span>一天内允许被呼叫{dayAllowableTimes}次</span>}
                {weekAllowableTimes && <span>一周内允许被呼叫{weekAllowableTimes}次</span>}
                {monthAllowableTimes && <span>一个月允许被呼叫{monthAllowableTimes}次</span>}
                {halfYearAllowableTimes && <span>六个月允许被呼叫{halfYearAllowableTimes}次</span>}
              </p>
            )}
          </div>
          {callLimitSwitch && (
            <div style={{ textAlign: 'center', width: 150 }}>
              <Switch checked={callLimitSwitch === 'on'} onChange={this.onSetChange} />
              {callLimitSwitch === 'on' && (
                <Button type="link" block onClick={this.openDetail} style={{ marginTop: 6 }}>
                  编辑
                </Button>
              )}
            </div>
          )}
        </div>
        <DetailModal
          visible={visibleDetail}
          callLimitDetail={callLimitDetail}
          successFn={async () => {
            if (!mode) {
              // 下一步-启用
              await this.updateSwitch(true);
            } else {
              message.success('修改成功');
            }
            this.closeDetail();
            this.fetchData();
          }}
          cancelFn={() => {
            this.closeDetail();
          }}
        ></DetailModal>
      </div>
    );
  }
}
